package com.ly.utils;

import com.ly.pojo.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
@Component
public class FastDfsUtil {
    //加载配置文件
    static {
        try {
            ClientGlobal.initByProperties("fdfs_client.conf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //[group1/M00/00/00/rBow72F4BqeAURmWAAGXfJmw-cg82..jpg] [group1, M00/00/00/rBow72F4BxeAI8HGAAAml1OdP2Q49..jpg]
    public static void downLoad(String group_name,String remote_filename) throws Exception {
        StorageClient storageClient = getStorageClient();
        byte[] bytes = storageClient.download_file(group_name, remote_filename);
        String uu = UUID.randomUUID().toString();
        FileOutputStream out = new FileOutputStream(new File("D:\\localFile\\" + uu + ".jpg"));
        out.write(bytes);
        out.close();
    }



    /**
     * 上传文件storage
     * @param file
     * @return
     * @throws Exception
     */
    public static String[] upLoadFile(FastDFSFile file) throws Exception {
        NameValuePair[] list = new NameValuePair[1];
        list[0] = new NameValuePair("文件名",file.getName());
        StorageClient storageServer = getStorageClient();
        String[] message = storageServer.upload_file(file.getBytes(), file.getExt(), list);
        System.out.println(message);
        return message;
    }



    /**
     *
     * @return 返回tracker服务
     * @throws Exception
     */
    public static TrackerServer getTrackerServer() throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

    /**
     * 获取storage客户端
     * @return
     * @throws Exception
     */
    public static StorageClient getStorageClient() throws Exception {
        StorageClient storageClient = new StorageClient(getTrackerServer(),null);
        return storageClient;
    }


}
